<template>
  <el-dialog :title="addOrEdit ? '新增目录' : '编辑目录'" :visible="showDialog" width="50%" @close="btnCancel">
    <el-form label-width="120px" ref="directoryForm" :model="formData" :rules="rules">
      <el-form-item label="所属学科" prop="subjectID" v-if="showSubject">
        <el-select style="width:70%" placeholder="请选择" v-model="formData.subjectID" @focus="getsubjectIDList">
          <el-option v-for="(item,index) in subjectIDList"
          :key="index"
          :label="item.label"
          :value="item.value" />
      </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="directoryName">
        <el-input style="width:70%" placeholder="请输入目录名称" v-model="formData.directoryName" />
      </el-form-item>
    </el-form>
     <!-- footer插槽 -->
     <template v-slot:footer>
      <el-row type="flex" justify="center">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
// 引入获取学科简单列表接口
import { simple } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/directorys.js'
export default {
  name: 'DirectoryAdd',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    addOrEdit: {
      type: Boolean
    },
    showSubject: {
      type: Boolean
    }
  },
  data () {
    return {
      // 定义表单数据
      formData: {
        subjectID: '',
        directoryName: ''
      },
      // 定义校验规则
      rules: {
        subjectID: [{ required: true, message: '请选择所属学科', trigger: 'blur' }],
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      },
      // 定义学科数据
      subjectIDList: []
    }
  },
  methods: {
    // 获取学科数据
    async getsubjectIDList () {
      const { data } = await simple()
      this.subjectIDList = data
    },
    // 点击确定
    async btnOK () {
      await this.$refs.directoryForm.validate()
      if (this.addOrEdit) {
        // 新增
        await add(this.formData)
      } else {
        // 编辑
        await update(this.formData)
      }
      this.$message.success(`${this.addOrEdit ? '添加' : '修改'}成功！`)
      this.$parent.getDirectoryData()
      this.$emit('update:showDialog', false)
    },
    // 点击取消
    btnCancel () {
      this.$refs.directoryForm.resetFields()
      this.formData = {
        subjectID: '',
        directoryName: ''
      }
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style scoped lang='less'></style>
